<template>
  <div>
    <!-- 搜索区域 -->
    <div style="margin-bottom: 20px">
      <el-input v-model="data.username" placeholder="请输入用户名" style="width: 200px" clearable></el-input>
      <el-input v-model="data.name" placeholder="请输入姓名" style="width: 200px; margin-left: 10px" clearable></el-input>
      <el-button type="primary" style="margin-left: 10px" @click="load">查询</el-button>
      <el-button type="primary" style="margin-left: 10px" @click="handleAdd">新增</el-button>
      <el-button type="danger" style="margin-left: 10px" :disabled="!data.ids.length" @click="delBatch">批量删除</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="sex" label="性别" />
      <el-table-column prop="major" label="专业" />
      <el-table-column prop="contactInfo" label="联系方式" />
      <el-table-column prop="descr" label="描述" />
      <el-table-column prop="clubNames" label="管理的社团" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div style="margin-top: 20px">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5, 10, 20]"
          layout="total, sizes, prev, pager, next"
          :total="data.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 表单对话框 -->
    <el-dialog v-model="data.formVisible" :title="data.form.id ? '编辑' : '新增'" width="500px">
      <el-form :model="data.form" label-width="100px" :rules="rules" ref="formRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="data.form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="data.form.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="data.form.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="data.form.major" placeholder="请输入专业"></el-input>
        </el-form-item>
        <el-form-item label="联系方式" prop="contactInfo">
          <el-input v-model="data.form.contactInfo" placeholder="请输入联系方式"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="descr">
          <el-input v-model="data.form.descr" type="textarea" placeholder="请输入描述"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!data.form.id">
          <el-input v-model="data.form.password" placeholder="请输入密码" type="password"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'

// 使用 reactive 统一管理数据，参考 Student-manage.vue
const data = reactive({
  username: null,
  name: null,
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  form: {},
  ids: [] // 用于批量删除
})

const formRef = ref(null)

// 表单验证规则，参考 Student-manage.vue 并调整
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
   major: [
    { required: true, message: '请输入专业', trigger: 'blur' }
  ],
   contactInfo: [
    { required: true, message: '请输入联系方式', trigger: 'blur' }
    // 可以根据需要添加手机号码格式验证
    // { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 加载数据，参考 Student-manage.vue 并调整接口和参数
const load = () => {
  request.get('/president/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      username: data.username ? `%${data.username}%` : null,
      name: data.name ? `%${data.name}%` : null
    }
  }).then(res => {
    data.tableData = res.data?.list || []
    data.total = res.data?.total || 0
  })
}



// 新增按钮点击，参考 Student-manage.vue
const handleAdd = () => {
  data.form = {}
  data.formVisible = true
}

// 编辑按钮点击，参考 Student-manage.vue
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row)) // 深拷贝
  data.formVisible = true
}

// 保存新增或编辑，参考 Student-manage.vue 并调整接口和方法
const save = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (data.form.id) {
        update() // 编辑
      } else {
        add() // 新增
      }
    }
  })
}

// 新增社长请求，参考 Student-manage.vue 并调整接口
const add = () => {
  request.post('/president/add', data.form).then(res => {
    if (res.code === '200') {
      data.formVisible = false
      ElMessage.success('新增成功')
      load()
    } else {
      ElMessage.error(res.msg || '新增失败')
    }
  }).catch(err => {
     ElMessage.error('新增失败')
     console.error(err)
  })
}

// 更新社长请求，参考 Student-manage.vue 并调整接口和方法 (PUT)
const update = () => {
  request.put('/president/updateById', data.form).then(res => {
    if (res.code === '200') {
      data.formVisible = false
      ElMessage.success('更新成功')
      load()
    } else {
      ElMessage.error(res.msg || '更新失败')
    }
  }).catch(err => {
     ElMessage.error('更新失败')
     console.error(err)
  })
}

// 删除单条社长请求，参考 Student-manage.vue 并调整接口
const del = (id) => {
  ElMessageBox.confirm('确认删除该社长吗？', '提示', {
    type: 'warning'
  }).then(() => {
    request.delete('/president/deleteById/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    }).catch(err => {
       ElMessage.error('删除失败')
       console.error(err)
    })
  }).catch(() => {})
}

// 批量删除社长请求，参考 Student-manage.vue 并调整接口
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning('请选择需要批量删除的数据')
    return
  }
  ElMessageBox.confirm('确认批量删除选中的社长吗？', '提示', {
    type: 'warning'
  }).then(() => {
    request.delete('/president/deleteBatch', { data: data.ids }).then(res => { // 批量删除DELETE请求需要将参数放在data里
      if (res.code === '200') {
        ElMessage.success('批量删除成功')
        load()
      } else {
        ElMessage.error(res.msg || '批量删除失败')
      }
    }).catch(err => {
       ElMessage.error('批量删除失败')
       console.error(err)
    })
  }).catch(() => {})
}

// 表格多选变化事件，参考 Student-manage.vue
const handleSelectionChange = (rows) => {
  data.ids = rows.map(row => row.id)
}

// 分页大小改变事件，参考 Student-manage.vue
const handleSizeChange = (val) => {
  data.pageSize = val
  load()
}

// 页码改变事件，参考 Student-manage.vue
const handleCurrentChange = (val) => {
  data.pageNum = val
  load()
}

// 页面加载时调用加载数据方法
onMounted(() => {
  load()
})

</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 可以添加一些通用样式来匹配，例如搜索区域的间距 */
.mb-4 {
  margin-bottom: 20px;
}

</style> 